/*******************************************************************************
 * Copyright (c) 2009, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/

package org.eclipse.ua.tests.help.util;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.help.internal.server.WebappManager;

public class LoadServletUtil {

	private static long uniqueParam = System.currentTimeMillis();

	/**
	 * Start a server for use in the performance tests
	 */
	public static void startServer() throws Exception {
		WebappManager.start("help");
		int port = WebappManager.getPort();
		URL url = new URL("http", "localhost", port, "/help/index.jsp");
		URLConnection connection = url.openConnection();
		setTimeout(connection, 5000);
		try (InputStream input = url.openStream()) {
			int firstbyte = input.read();
			assertThat(firstbyte).isGreaterThan(0);
		}
	}

	/**
	 * Stop the server created by startServer()
	 */
	public static void stopServer() throws CoreException {
		WebappManager.stop("help");
	}

	/**
	 * Read an html page generated by a servlet
	 * @param paragraphs the number of paragraphs in the page
	 */
	public static void readLoadServlet(int paragraphs) throws Exception {
		int port = WebappManager.getPort();
		// Use a unique parameter to defeat caching
		++uniqueParam;
		URL url = new URL("http", "localhost", port,
				"/help/loadtest?value=" + uniqueParam + "&repeat=" + paragraphs);
		try (InputStream input = url.openStream()) {
			int nextChar;
			long value = 0;
			// The loadtest servlet returns the uniqueParam in an opening
			// comment such as <!--1234-->
			// Read this to verify that we are not getting a cached page
			boolean inFirstComment = true;
			do {
				nextChar = input.read();
				if (inFirstComment) {
					if (nextChar == '>') {
						inFirstComment = false;
					} else if (Character.isDigit((char) nextChar)) {
						value = value * 10 + (nextChar - '0');
					}
				}
			} while (nextChar != '$');
			assertEquals(uniqueParam, value);
		}
	}

	private static void setTimeout(URLConnection conn, int milliseconds) {
		conn.setConnectTimeout(milliseconds);
		conn.setReadTimeout(milliseconds);
	}

}
